<template>
  <a-modal
    :visible="visible"
    :mask-closable="false"
    :unmount-on-close="true"
    @cancel="cancel"
    @ok="submitData"
  >
    <template #title> 添加审阅 </template>
    <div class="content">
      <a-form :model="formData" ref="formRef" label-align="left" :rules="rules">
        <a-row :gutter="12">
          <a-col :span="24">
            <a-form-item
              field="processId"
              label="选择流程"
              label-col-flex="80px"
              :validate-trigger="['change', 'input']"
            >
              <a-select v-model="formData.processId" placeholder="请选择流程">
                <a-option
                  v-for="template in processList"
                  :key="`${template.id}-${template.name}`"
                  :value="template.id"
                  :label="template.name"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="12">
          <a-col :span="24">
            <a-form-item
              field="name"
              label="审阅名称"
              label-col-flex="80px"
              :validate-trigger="['change', 'input']"
            >
              <a-input v-model="formData.name" placeholder="请输入名称" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider />
        <a-row :gutter="12">
          <a-col :span="24">
            <div class="title">
              <div class="text">
                <img
                  src="@/assets/images/check/Frame@2x.png"
                  alt=""
                  style="width: 17px; height: 17px"
                />
                <span class="text-font">需审阅文件</span>
              </div>
              <div class="file-count">
                <span>总计：{{ fileCounts || 0 }} 个文件</span>
                <a-button type="text" @click="treeFolderVisible = true">
                  添加文件
                </a-button>
              </div>
            </div>
            <div class="file-list-wrap">
              <FileCollapse
                v-if="fileList.length"
                :files="fileList"
              ></FileCollapse>
            </div>
          </a-col>
        </a-row>
      </a-form>
      <TreeFolder
        v-model:visible="treeFolderVisible"
        :ok-function="fileChange"
        :config="{ type: 1 }"
      ></TreeFolder>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import {
    computed,
    defineEmits,
    defineProps,
    onMounted,
    ref,
    watch,
  } from 'vue';
  import FileCollapse from '@/views/check/components/file-collapse/index.vue';
  import TreeFolder from '@/components/tree-folder/index.vue';
  import { useRoute } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { getDirectoryFileCounts, getDirectoryFileIds } from '../../api';
  import { getProcess, addCheck } from './api';

  interface ProcessObj {
    id?: string | number;
    name?: string;
  }

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    files: {
      type: Array,
      default() {
        return [];
      },
    },
  });
  const emits = defineEmits(['update:visible', 'submit']);
  const route = useRoute();
  const processList = ref<ProcessObj[]>([]);
  const getProcessList = () => {
    const params = {
      pageNo: 1,
      pageSize: 100000,
      projectId: route.params.projectId,
    };
    getProcess(params)
      .then((res: any) => {
        if (res.code === 8000000) {
          processList.value = res.data.list || [];
        }
      })
      .catch((e) => {
        if (e) {
          processList.value = [];
        }
      });
  };
  const formRef = ref();
  const formData = ref({
    name: '',
    processId: '',
  });
  const rules = ref({
    name: [
      {
        required: true,
        message: '请输入名称',
      },
    ],
    processId: [
      {
        required: true,
        message: '请选择流程',
      },
    ],
  });
  const fileList = ref([]);

  const fileCounts = computed(() => {
    let counts = 0;
    fileList?.value?.forEach((file) => {
      counts += getDirectoryFileCounts(file);
    });
    return counts;
  });
  const fileIds = computed(() => {
    const counts: any[] = getDirectoryFileIds(fileList.value);
    // console.log('ids: ', counts);
    return counts;
  });
  const treeFolderVisible = ref(false);
  const fileChange = async (data: () => Promise<any>) => {
    const files = await data();
    fileList.value = files;
  };

  const cancel = () => {
    fileList.value = [];
    emits('update:visible', false);
  };
  const submitData = async () => {
    const params = {
      name: formData.value.name,
      cdeProcessId: formData.value.processId,
      fileIds: fileIds.value,
      projectId: route.params.projectId,
      fileCount: fileCounts.value,
      formKey: 'SHENYUE',
    };
    await formRef.value?.validate();
    // console.log('ids: ', params);
    if (!params.name || !params.cdeProcessId) {
      Message.error('请完善审阅名称或流程信息');
    } else if (!params.fileCount) {
      Message.error('请选择文件');
    } else {
      addCheck(params).then((res: any) => {
        if (res.code === 8000000) {
          Message.success('创建成功！');
          emits('submit', true);
          cancel();
        }
      });
    }
  };

  const init = () => {
    formData.value = {
      name: '',
      processId: '',
    };
    if (Array.isArray(props.files) && props.files?.length) {
      fileList.value = JSON.parse(JSON.stringify(props.files));
    }
    getProcessList();
  };
  watch(
    () => props.visible,
    (val) => {
      if (val) {
        init();
      }
    }
  );
</script>

<style scoped lang="less">
  .title {
    position: relative;
    .text {
      display: flex;
      align-content: center;
      align-items: center;
    }
    .text-font {
      display: inline-block;
      font-size: 16px;
      font-weight: 600;
      margin-left: 8px;
    }
    .file-count {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  .file-list-wrap {
    margin-top: 16px;
    min-height: 20px;
  }
</style>
